package casa.depesos.app.com.utils;

import static android.text.Spanned.SPAN_EXCLUSIVE_INCLUSIVE;

import android.annotation.SuppressLint;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.Matrix;
import android.hardware.camera2.CameraManager;
import android.net.Uri;
import android.os.Build;
import android.provider.Settings;
import android.telephony.TelephonyManager;
import android.text.InputFilter;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.TextUtils;
import android.text.method.LinkMovementMethod;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.webkit.WebView;
import android.widget.EditText;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.core.content.PermissionChecker;

import com.common.base.utils.SPHelper;
import com.google.gson.Gson;
import com.menu.myapplication.BuildConfig;
import com.mo.xi.ge.info.DaleInfoInstance;
import com.support.toast.ToastUtil;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import casa.depesos.app.com.App;
import casa.depesos.app.com.activity.WebActivity;
import casa.depesos.app.com.http.data.Usr;
import casa.depesos.app.com.it.CompressListener;

public class Utils {

    public static int px2sp(Context context, float pxValue) {
        final float fontScale = context.getResources().getDisplayMetrics().scaledDensity;
        return (int) (pxValue / fontScale + 0.5f);
    }

    public static int px2dip(Context context, float pxValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (pxValue / scale + 0.5f);
    }

    public static int getStatusBarHeight(Context c) {
        int result = 0;
        Resources resources = c.getResources();
        int resourceId = resources.getIdentifier("status_bar_height", "dimen", "android");
        if (resourceId > 0) {
            result = resources.getDimensionPixelSize(resourceId);
        }
        return result;
    }

    public static int dp2Px(Context context, float dipValue) {
        final float scale = context.getResources()
                .getDisplayMetrics().density;
        int pxValue = (int) (dipValue * scale + 0.5f);

        return pxValue;
    }

    public static int getScreenWidth() {
        DisplayMetrics dm = new DisplayMetrics();
        ((WindowManager) App.getApp()
                .getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay()
                .getMetrics(dm);
        return dm.widthPixels;
    }

    public static int getScreenHeight() {
        DisplayMetrics dm = new DisplayMetrics();
        ((WindowManager) App.getApp()
                .getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay()
                .getMetrics(dm);
        return dm.heightPixels;
    }

    public static int getScreenRealHeight() {
        DisplayMetrics dm = new DisplayMetrics();
        ((WindowManager) App.getApp()
                .getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay()
                .getRealMetrics(dm);
        return dm.heightPixels;
    }

    public static boolean isSquare() {
        try {
            DisplayMetrics dm = new DisplayMetrics();
            ((WindowManager) App.getApp()
                    .getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay()
                    .getMetrics(dm);
            int w = dm.widthPixels;
            int h = dm.heightPixels;
            return Math.max(w, h) / (Math.min(w, h) * 1.0f) <= 1.5f;
        } catch (Throwable e) {
            return false;
        }
    }

    //改变bitmap尺寸的方法
    public static Bitmap zoomImg(Bitmap bm, int newWidth, int newHeight) {
        // 获得图片的宽高
        int width = bm.getWidth();
        int height = bm.getHeight();
        // 计算缩放比例
        float scaleWidth = ((float) newWidth) / width;
        float scaleHeight = ((float) newHeight) / height;
        // 取得想要缩放的matrix参数
        Matrix matrix = new Matrix();
        matrix.postScale(scaleWidth, scaleHeight);
        // 得到新的图片
        Bitmap newbm = Bitmap.createBitmap(bm, 0, 0, width, height, matrix, true);
        return newbm;
    }

    public static void compressImageByPixel(Uri image, String out, CompressListener listener) throws Throwable {
        BitmapFactory.Options newOpts = new BitmapFactory.Options();
        newOpts.inJustDecodeBounds = true;//只读边,不读内容
        InputStream in = App.getApp().getContentResolver().openInputStream(image);
        BitmapFactory.decodeStream(in, null, newOpts);
        in.close();
        newOpts.inJustDecodeBounds = false;
        int width = newOpts.outWidth;
        int height = newOpts.outHeight;
        float maxSize = 800;
        int be = 1;
        if (width >= height && width > maxSize) {//缩放比,用高或者宽其中较大的一个数据进行计算
            be = (int) (newOpts.outWidth / maxSize);
            be++;
        } else if (width < height && height > maxSize) {
            be = (int) (newOpts.outHeight / maxSize);
            be++;
        }
        newOpts.inSampleSize = be;//设置采样率
        newOpts.inPreferredConfig = Bitmap.Config.ARGB_8888;//该模式是默认的,可不设
        newOpts.inPurgeable = true;// 同时设置才会有效
        newOpts.inInputShareable = true;//。当系统内存不够时候图片自动被回收
        Bitmap bitmap;
        in = App.getApp().getContentResolver().openInputStream(image);
        bitmap = BitmapFactory.decodeStream(in, null, newOpts);
        in.close();
        File thumbnailFile = new File(out);
        bitmap.compress(Bitmap.CompressFormat.JPEG, 100, new FileOutputStream(thumbnailFile));
        listener.onCompressSuccess(thumbnailFile);
    }

    public static boolean hasCamera() {
        try {
            CameraManager manager = (CameraManager) App.getApp().getSystemService(Context.CAMERA_SERVICE);
            String[] ids = manager.getCameraIdList();
            for (String id : ids) {
                try {
                    manager.getCameraCharacteristics(id);
                } catch (Throwable e) {
                    e.printStackTrace();
                    continue;
                }
                return true;
            }
        } catch (Throwable e) {
            e.printStackTrace();
        }
        return false;
    }

    public static boolean checkSelfPermission(@NonNull Context context, @NonNull String permission) {
        return context.checkSelfPermission(permission) == PackageManager.PERMISSION_GRANTED;
    }

    public static void hideInput(View v) {
        InputMethodManager imm = (InputMethodManager) v.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
        if (imm.isActive()) {
            imm.hideSoftInputFromWindow(v.getApplicationWindowToken(), 0);
        }
    }

    static Usr usr = null;
    static String phone2 = "";

    public static void reset() {
        usr = null;
        phone2 = "";
        Constant.white = false;
        Utils.setStatus(10);
    }

    public static int getStatus() {
        return SPHelper.getInstance(App.getApp()).getInt("whiteStatus", 10);
    }

    public static void setStatus(int status) {
        SPHelper.getInstance(App.getApp()).putInt("whiteStatus", status).commit();
    }

    public static String getToken() {
        if (usr == null) {
            String str = SPHelper.getInstance(App.getApp()).getString("usr", null);
            if (str == null) {
                return "";
            }
            usr = new Gson().fromJson(str, Usr.class);
            DaleInfoInstance.Companion.get(App.getApp()).setUsrId(usr.uid);
            Constant.white = usr.isAdmin;
            if (!TextUtils.isEmpty(usr.phone)) {
                String s1 = usr.phone.substring(0, 3);
                int len = usr.phone.length();
                String s2 = usr.phone.substring(len - 3, len);
                StringBuffer sb = new StringBuffer(s1);
                for (int i = 0; i < len - 6; i++) {
                    sb.append("*");
                }
                sb.append(s2);
                phone2 = sb.toString();
            }
        }
        return usr == null || usr.token == null ? "" : usr.token;
    }

    public static String getPhone2() {
        if (TextUtils.isEmpty(phone2)) {
            getToken();
        }
        return phone2;
    }

    public static String getPhone() {
        if (usr == null) {
            getToken();
        }
        return usr == null || usr.phone == null ? "" : usr.phone;
    }

    public static String getUid() {
        if (usr == null) {
            getToken();
        }
        return usr == null || usr.uid == null ? "" : usr.uid;
    }

    public static void print(String msg) {
        if (!BuildConfig.DEBUG) {
            return;
        }
        Log.e("log_debug", msg);
    }

    public static boolean isChinese(String str) {
        String regex = "[\\u4e00-\\u9fa5]+";
        return str.matches(regex);
    }

    public static void freeWeb(WebView wb) {
        try {
            if (wb == null) {
                return;
            }
            if (wb.getParent() instanceof ViewGroup) {
                ((ViewGroup) wb.getParent()).removeView(wb);
            }
            wb.setWebChromeClient(null);
            wb.setWebViewClient(null);
            wb.removeAllViews();
            wb.destroy();
        } catch (Throwable e) {

        }
    }

    public final static boolean isHw() {
        return a("huawei", "honor", "华为");
    }

    public final static boolean isXm() {
        return a("xiaomi");
    }

    public static boolean a(String... strArr) {
        String str = Build.BRAND;
        if (str == null) {
            str = "";
        }
        str = str.toLowerCase();
        String str2 = Build.MANUFACTURER;
        if (str2 == null) {
            str2 = "";
        }
        str2 = str2.toLowerCase();

        for (String str3 : strArr) {
            if (str.contains(str3) || str2.contains(str3)) {
                return true;
            }
        }
        return false;
    }

    public static void setClickableText(TextView agree, String url, View.OnClickListener listener) {
        String str = agree.getText().toString();
        SpannableString ss = new SpannableString(str);
        MyClickableSpan s = new MyClickableSpan(App.getApp(), url, listener);
        int i1 = str.indexOf("<");
        int e1 = str.indexOf(">") + 1;
        ss.setSpan(s, i1, e1, SPAN_EXCLUSIVE_INCLUSIVE);
        agree.setMovementMethod(LinkMovementMethod.getInstance());
        agree.setHighlightColor(Color.TRANSPARENT);
        agree.setText(ss);
    }

    public static String getHour(long time) {
        Date d = new Date(time);
        SimpleDateFormat sdf = new SimpleDateFormat("HH:mm");
        String day = sdf.format(d);
        return day;
    }

    public static String getDay(String str) {
        try {
            Date d = new Date(Long.parseLong(str));
            SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
            String day = sdf.format(d);
            return day;
        } catch (Throwable e) {
            e.printStackTrace();
            return str;
        }
    }

    public static String getDay3(String str) {
        try {
            Date d = new Date(Long.parseLong(str));
            SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy");
            String day = sdf.format(d);
            return day;
        } catch (Throwable e) {
            e.printStackTrace();
            return str;
        }
    }

    public static String getDay2(String str) {
        try {
            Date d = new Date(Long.parseLong(str));
            SimpleDateFormat sdf = new SimpleDateFormat("MM.dd.yyyy HH:mm:ss");
            String day = sdf.format(d);
            return day;
        } catch (Throwable e) {
            e.printStackTrace();
            return str;
        }
    }

    public static String getHour2(long time) {
        Date d = new Date(time);
        SimpleDateFormat sdf = new SimpleDateFormat("ssmmHH");
        String day = sdf.format(d);
        return day;
    }

    /*** 禁止EditText输入空格和换行符** @param editText EditText输入框*/
    public static void setEditTextInputSpace(EditText editText, int max) {
        InputFilter filter = new InputFilter() {
            @Override
            public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
                if (source.equals(" ") || source.toString().contentEquals("\n")) {
                    return "";
                } else {
                    return null;
                }
            }
        };
        editText.setFilters(new InputFilter[]{filter, new InputFilter.LengthFilter(max)});
        String tmp = editText.getText().toString();
        if (tmp.length() > max) {
            tmp = tmp.substring(0, max);
            editText.setText(tmp);
        }
    }

    public static void setNumberEditTextInputSpace(EditText editText, int max) {
        InputFilter filter = new InputFilter() {
            @Override
            public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
                try {
                    Long.valueOf(source.toString());
                    return null;
                } catch (Throwable e) {
                    return "";
                }
            }
        };
        editText.setFilters(new InputFilter[]{filter, new InputFilter.LengthFilter(max)});
        String tmp = editText.getText().toString();
        if (tmp.length() > max) {
            tmp = tmp.substring(0, max);
            editText.setText(tmp);
        }
    }

    public static void setEditTextInputNoSpaceStart(EditText editText, int max) {
        InputFilter filter = new InputFilter() {
            @Override
            public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
                if (source.equals(" ") || source.toString().contentEquals("\n")) {
                    if (dest.toString().isEmpty()) {
                        return "";
                    }
                }
                return null;
            }
        };
        editText.setFilters(new InputFilter[]{filter, new InputFilter.LengthFilter(max)});
    }

    public static boolean isEmail(String email) {
        if (null == email || "".equals(email)) return false;
        //Pattern p = Pattern.compile("\\w+@(\\w+.)+[a-z]{2,3}"); //简单匹配
        Pattern p = Pattern.compile("\\w+([-+.]\\w+)*@\\w+([-.]\\w+)*\\.\\w+([-.]\\w+)*");//复杂匹配
        Matcher m = p.matcher(email);
        return m.matches();
    }

    public final static void copy(String str) {
        copy(str, true);
    }

    public final static void copy(String str, boolean showTip) {        //获取剪贴板管理器：
        ClipboardManager cm = (ClipboardManager) App.getApp().getSystemService(Context.CLIPBOARD_SERVICE);
// 创建普通字符型ClipData
        ClipData mClipData = ClipData.newPlainText("Label", str);
// 将ClipData内容放到系统剪贴板里。
        cm.setPrimaryClip(mClipData);
        if (showTip) {
            ToastUtil.showShortToast(App.getApp(), "Copiado");
        }
    }

    public static String format(String num) {
        try {
            DecimalFormat myformat = new DecimalFormat();
            myformat.applyPattern(",##0.00");
            return myformat.format(Double.parseDouble(num));
        } catch (Throwable e) {

        }
        return num;
    }

    public static String formatNoFloat(String s) {
        return formatNoFloat(s, false);
    }

    public static String formatNoFloat(String s, boolean unit) {
        try {
            NumberFormat f = NumberFormat.getNumberInstance();
            s = f.format(Float.valueOf(s));
        } catch (Throwable e) {
            if (TextUtils.isEmpty(s)) {
                s = "--";
            }
        }
        if (unit) {
            return "$" + s;
        }
        return s;
    }

    public static void setEditTextEmail(EditText searchEdit, int max) {
        InputFilter typeFilter = new InputFilter() {
            @Override
            public CharSequence filter(
                    CharSequence source,
                    int start,
                    int end,
                    Spanned dest,
                    int dstart,
                    int dend
            ) {
                Pattern p = Pattern.compile("[0-9a-zA-Z|!@.\\-_]+");
                Matcher m = p.matcher(source.toString());
                if (!m.matches()) return "";
                return null;
            }
        };
        //如果要限制输入字数，数组中加上new InputFilter.LengthFilter(maxLength)
        searchEdit.setFilters(new InputFilter[]{typeFilter, new InputFilter.LengthFilter(max)});
    }

    public static boolean saveImageTo(Bitmap bmp, String path) {
        //获取文件
        File file = new File(path);
        file.getParentFile().mkdirs();
        FileOutputStream fos = null;
        try {
            fos = new FileOutputStream(file);
            bmp.compress(Bitmap.CompressFormat.JPEG, 100, fos);
            fos.flush();
            Log.e("picture", "保存成功");
            return true;
        } catch (Exception e) {
            Log.e("bitmaperr", e.getMessage());
            e.printStackTrace();
        } finally {
            try {
                if (fos != null) {
                    fos.close();
                }
            } catch (Exception e) {
                Log.e("bitmaperr", e.getMessage());
                e.printStackTrace();
            }
        }
        return false;
    }

    public static boolean hasPermissions(Context context, String... permission) {
        for (String s : permission) {
            if (!hasPermission(context, s)) {
                return false;
            }
        }
        return true;
    }

    public static boolean hasPermission(Context context, String... permissions) {
        try {
            for (String permission : permissions) {
                if (PermissionChecker.checkSelfPermission(context, permission) != PermissionChecker.PERMISSION_GRANTED) {
                    return false;
                }
            }
            return true;
        } catch (RuntimeException t) {
            return false;
        }
    }

    public static String getMsgTime(String time) {
        if (isToday(time)) {
            return Utils.getHour(Long.parseLong(time));
        } else {
            return Utils.getDay(time);
        }
    }

    private static boolean isToday(String time) {
        try {
            Calendar c = Calendar.getInstance();
            c.setTimeInMillis(Long.parseLong(time));
            Calendar c2 = Calendar.getInstance();
            c2.setTimeInMillis(System.currentTimeMillis());
            if (c2.get(Calendar.YEAR) == c.get(Calendar.YEAR)
                    && c2.get(Calendar.DAY_OF_YEAR) == c.get(Calendar.DAY_OF_YEAR)) {
                return true;
            }
        } catch (Throwable e) {
            e.printStackTrace();
        }
        return false;
    }

    public static String getDeviceId() {
        String id = getIMEI(App.getApp());
        if (TextUtils.isEmpty(id)) {
            return getAndroidId(App.getApp());
        }
        return id;
    }

    static String imei = null;

    @SuppressLint("MissingPermission")
    public static String getIMEI(Context context) {
        try {
            if (!TextUtils.isEmpty(imei)) {
                return imei;
            }
            TelephonyManager manager = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
            if (imei == null) {
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                    imei = manager.getImei();
                }
                if (TextUtils.isEmpty(imei)) {
                    imei = manager.getDeviceId();
                }
            }
            if (imei == null) {
                imei = "";
            }
            return imei;
        } catch (Exception e) {
            e.printStackTrace();
            return "";
        }
    }

    static String androidId = null;

    public static String getAndroidId(Context context) {
        if (androidId != null) {
            return androidId;
        }
        String tmp;
        try {
            tmp = Settings.Secure.getString(context.getContentResolver(), Settings.Secure.ANDROID_ID);
            if ("9774d56d682e549c".equals(tmp)) {
                tmp = null;
            }
        } catch (Throwable e) {
            tmp = null;
        }
        if (tmp == null) {
            androidId = "";
        } else {
            androidId = tmp;
        }
        return androidId;
    }

    public static void toMsg() {
        Intent i = new Intent(App.getApp(), WebActivity.class);
        i.putExtra("url", Constant.MSG);
        i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        App.getApp().startActivity(i);
    }

    public static long getRefuseCountDown() {
        long l = SPHelper.getInstance(App.getApp()).getLong("white_refuse", -1);
        if (l == -1) {
            long tmp = 14 * 24 * 3600 * 1000;
            setRefuseCountDown(tmp);
            return tmp;
        } else {
            long tmp = SPHelper.getInstance(App.getApp()).getLong("white_refuse_set", System.currentTimeMillis());
            long pass = System.currentTimeMillis() - tmp;
            l -= pass;
            return Math.max(l, 0);
        }
    }

    public static void setRefuseCountDown(long time) {
        SPHelper.getInstance(App.getApp()).putLong("white_refuse", time);
        SPHelper.getInstance(App.getApp()).putLong("white_refuse_set", System.currentTimeMillis()).commit();
    }
}
